package com.webchat.pgc.service.mall;


import com.webchat.common.enums.mall.MallSourceTypeEnum;
import com.webchat.pgc.repository.dao.mall.IMallImageDAO;
import com.webchat.pgc.repository.entity.mall.MallImage;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class MallImageService {


    @Autowired
    private IMallImageDAO mallImageDAO;


    @Transactional
    public boolean save(MallSourceTypeEnum sourceType, Long sourceId, List<String> images) {

        Integer type = sourceType.getType();
        mallImageDAO.deleteAllBySourceTypeAndSourceId(type, sourceId);
        if (CollectionUtils.isEmpty(images)) {
            return false;
        }
        AtomicInteger idx = new AtomicInteger(1);
        List<MallImage> mallImages = images.stream().map(img -> {
            int index = idx.get();
            MallImage mallImage = new MallImage();
            mallImage.setSourceType(type);
            mallImage.setSourceId(sourceId);
            mallImage.setImage(img);
            mallImage.setMainImage(index == 1);
            mallImage.setSort(index);
            idx.getAndIncrement();
            return mallImage;
        }).toList();
        mallImageDAO.saveAll(mallImages);
        return true;
    }

    /**
     * 根据资源类型、资源id获取图片配置
     *
     * @param sourceType
     * @param sourceId
     * @return
     */
    public List<String> getImagesBySourceTypeAndId(MallSourceTypeEnum sourceType,
                                                   Long sourceId) {
        List<MallImage> images = mallImageDAO.findAllBySourceTypeAndSourceIdOrderByMainImageDescSortAsc(
                                 sourceType.getType(), sourceId);
        if (CollectionUtils.isEmpty(images)) {
            return Collections.emptyList();
        }
        return images.stream().map(MallImage::getImage).collect(Collectors.toList());
    }

}
